package com.movecar.ui;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.listview.WaterFallListView;
import com.movecar.model.EventBusBean;
import com.movecar.model.GroupBean;
import com.movecar.model.ThemeFiltrateBean;
import com.movecar.model.ThemeFiltrateListBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import de.greenrobot.event.EventBus;

/**
 * 浮云主题筛选列表
 * 
 * @author Zhao.JQ
 * 
 */
public class ThemeFiltrateActivity extends Activity implements OnClickListener {
	protected WaterFallListView mXList;
	private ThemeFiltrateBean mThemeFiltrateBean;
	private CustomProgressDialog progressDialog = null;
	private ImageLoader imageLoader = null;
	private RelativeLayout main_relative;
	private ThemeFiltrateAdapter mThemeFiltrateAdapter;
	private View mainView;
	private LayoutInflater layoutInflater;
	private Button ok;
	private String idStr;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mainView = layoutInflater.inflate(R.layout.theme_filtrate, null);
		setContentView(mainView);
		imageLoader = ImageLoader.getInstance();

		initView();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initView() {
		TextView title = (TextView) findViewById(R.id.title);
		main_relative = (RelativeLayout) findViewById(R.id.main_relative);
		title.setText("主题筛选");

		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		ok = (Button) findViewById(R.id.ok);
		ok.setOnClickListener(this);
		mXList = (WaterFallListView) findViewById(R.id.theme_filtrate_list);
		mXList.setPullLoadEnable(false);
		mXList.setPullRefreshEnable(false);
		mThemeFiltrateAdapter = new ThemeFiltrateAdapter(ThemeFiltrateActivity.this, mXList);
		mXList.setAdapter(mThemeFiltrateAdapter);
		startProgressDialog();
		getThemeFiltrateData();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			finish();
			break;
		case R.id.ok:
			startProgressDialog();
			StringBuffer sb = new StringBuffer();
			for (ThemeFiltrateListBean bean : mThemeFiltrateBean.getFtList()) {
				sb.append("-");
				sb.append(bean.getPmId());
				sb.append(",");
				sb.append(bean.getSelected());
			}
			idStr = sb.substring(1, sb.length());
			DoThemeFiltrate(idStr);
			break;
		default:
			break;
		}

	}
	


	/**
	 * 确定筛选
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void DoThemeFiltrate(String idStr) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "screenThemeNew2")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("idStr", idStr));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				if ("0".equals(result)) {
					setResult(RESULT_OK);
					finish();

				} else {
					stopProgressDialog();
					Alert.error(ThemeFiltrateActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(ThemeFiltrateActivity.this, "与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	/**
 * 
 */
	@SuppressWarnings("unchecked")
	private void getThemeFiltrateData() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "filterThemeNew2")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				main_relative.setVisibility(View.VISIBLE);

				Gson gson = new Gson();
				String result = (String) object;
				try {
					mThemeFiltrateBean = gson.fromJson(result, ThemeFiltrateBean.class);
				} catch (Exception e) {
					return;
				}

				if (mThemeFiltrateBean != null) {

					if (mThemeFiltrateBean.getFtList().size() == 0) {
						Alert.warn(ThemeFiltrateActivity.this, "目前无内容");

					}
					mThemeFiltrateAdapter.addItemTop(mThemeFiltrateBean.getFtList());

				} else {
					stopProgressDialog();
					Alert.error(ThemeFiltrateActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();

				Alert.error(ThemeFiltrateActivity.this, "与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public class ThemeFiltrateAdapter extends BaseAdapter {
		private Context mContext;
		private LinkedList<ThemeFiltrateListBean> mInfos;
		private LayoutInflater inflater;

		public ThemeFiltrateAdapter(Context context, WaterFallListView xListView) {
			mContext = context;
			mInfos = new LinkedList<ThemeFiltrateListBean>();
			inflater = LayoutInflater.from(mContext);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			ViewHolder viewHolder;
			final ThemeFiltrateListBean mThemeFiltrateListBean = mInfos.get(position);

			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = inflater.inflate(R.layout.theme_filtrate_item, null);

				viewHolder.theme_filtrate_title_img = (ImageView) convertView
						.findViewById(R.id.theme_filtrate_title_img);
				viewHolder.theme_filtrate_title = (TextView) convertView.findViewById(R.id.theme_filtrate_title);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			if ("0".equals(mThemeFiltrateListBean.getSelected())) {
				viewHolder.theme_filtrate_title.setTextColor(mContext.getResources().getColor(R.color.main_title));
				viewHolder.theme_filtrate_title.setText(mThemeFiltrateListBean.getTitle());
				viewHolder.theme_filtrate_title_img.setImageResource(R.drawable.filtrate_detail);
			} else if ("1".equals(mThemeFiltrateListBean.getSelected())) {
				viewHolder.theme_filtrate_title.setTextColor(mContext.getResources().getColor(R.color.gray));
				viewHolder.theme_filtrate_title.setText(mThemeFiltrateListBean.getTitle());
				viewHolder.theme_filtrate_title_img.setImageResource(R.drawable.filtrate_detail_click);
			} else {

			}
			refesh();
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					if ("0".equals(mThemeFiltrateListBean.getSelected())) {
						mThemeFiltrateListBean.setSelected("1");
					} else if ("1".equals(mThemeFiltrateListBean.getSelected())) {
						mThemeFiltrateListBean.setSelected("0");
					} else {

					}
					
					refesh();

				}

			});
			return convertView;
		}

		class ViewHolder {
			ImageView theme_filtrate_title_img;
			TextView theme_filtrate_title;

		}

		@Override
		public int getCount() {
			return mInfos.size();
		}

		@Override
		public Object getItem(int arg0) {
			return mInfos.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public void addItemLast(List<ThemeFiltrateListBean> datas) {
			mInfos.addAll(datas);
		}

		public void addItemTop(List<ThemeFiltrateListBean> datas) {
			mInfos.clear();
			for (ThemeFiltrateListBean info : datas) {
				mInfos.addLast(info);
			}
		}

		public void refesh() {
			this.notifyDataSetChanged();
		}
	}

	
}
